import 'dart:collection';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:group_button/group_button.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/LjgmOrder.dart';
import 'package:shop/shop/life/YuYueService.dart';

import 'Login.dart';

/**
 * 服务型商品详情页面
 */
class ServiceDetail extends StatefulWidget {
  String gid; //服务ID
  ServiceDetail({Key key, this.gid}) : super(key: key);

  @override
  _ServiceDetail createState() => _ServiceDetail(gid);
}

class _ServiceDetail extends State<ServiceDetail> {

  String gid;           //服务ID
  String userId;        //用户ID
  String merchantId;    //商户ID
  var obj = {};         //查询的商品
  bool guanzhu = false; //用户是否关注该商品服务
  List _imageUrls = []; //商品图片集合
  // List _imageUrls = ["http://b1-q.mafengwo.net/s9/M00/A5/88/wKgBs1d2ByKAXc2JAACsSNXA-sA34.jpeg","http://b1-q.mafengwo.net/s9/M00/A3/F0/wKgBs1d2BFyAceutAADiqnHT0ys50.jpeg"]; //定义图片存储的数组

  // 构造方法
  _ServiceDetail(gid) {
    this.gid=gid;
    _onLoading(gid);
  }

  var guige; // 商品的规格
  double money = 0.00; // 规格里选的价格
  var params = []; //规格下标
  var names = []; //选中的规格
  var panduan = []; //判断规格是否选重复
  String guiges = ""; //字符串规格
  String guigexiabiao = ""; //字符串规格下标
  dynamic funCb;

  // 获取数据
  void _onLoading(gid) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    String url = "/waimai/mGoods/getMGoodsById?id=" + gid;
    var x = await HttpUtil().get(url);
    if (x['code'] == 200) {
      obj = x['data'];
      String gDetail = x['data']['gdetail'];
      String url = Config.getInstance().getHost();
      obj['gdetail'] = gDetail.replaceAll("src=\"/images/goods", "src=\"${url}images/goods");
      for (int i = 0; i < x['data']['goodsImageList'].length; i++) {
        _imageUrls.add(url + x['data']['goodsImageList'][i]['picture']);
      }
    }
    var y = await HttpUtil().get("/waimai/merchant/merchantGuanzhu?userId="+userId+"&gid="+gid+"&type=1");
    if(y['code']==200){
      guanzhu = y['data'];
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return new Scaffold(
      appBar: AppBar(
        title: Text("服务介绍"),
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              child: ListView(
                children: [
                  Container(
                    // 轮播图
                    width: ScreenUtil().setHeight(464),
                    height: ScreenUtil().setHeight(232),
                    child: Swiper(
                      key: UniqueKey(),
                      // 解决轮播图片大于3个的问题，是否有效待核实
                      itemBuilder: _swiperBuilder,
                      itemCount: _imageUrls.length,
                      pagination: new SwiperPagination(
                          builder: DotSwiperPaginationBuilder(
                            color: Colors.black54,
                            activeColor: Colors.white,
                          )),
                      // control: SwiperControl(),
                      scrollDirection: Axis.horizontal,
                      autoplay: true,
                      autoplayDelay: 3000,
                      onTap: (index) => print('点击了第$index个'))),
                  Container(
                    // 商品信息
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(obj['gname']==null ? "" : obj['gname'],style: TextStyle(fontSize: 18,fontWeight: FontWeight.w600),),
                                  Text("月销量:"+obj['gsellnum'].toString())
                                ],
                              ),
                            )
                          ],
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(6, 3, 6, 3),
                          child: Row(children: [Expanded(
                            child: Text(obj['jianjie']==null ? "" : obj['jianjie'],style: TextStyle(fontSize: 18),),
                          )]),
                          decoration: BoxDecoration(),
                        ),
                      ],
                    ),
                  ),
                  Html(
                    data: """${obj['gdetail']}""", // 富文本中的详情
                    style: {
                      // "html": Style(
                      //   backgroundColor: Colors.black12,
                      // ),
                    },
                  )
                  // CachedNetworkImage(imageUrl: "http://p1-q.mafengwo.net/s9/M00/A3/C4/wKgBs1d2BBSALZsrAAUvBbAQKIo53.jpeg"),
                  // CachedNetworkImage(imageUrl: "http://t1-q.mafengwo.net/s9/M00/A3/D0/wKgBs1d2BCiABotSAACYtaAgjF469.jpeg"),
                  // CachedNetworkImage(imageUrl: "http://p1-q.mafengwo.net/s9/M00/A6/38/wKgBs1d2CG2AZiKYAAEFwiy-q6w20.jpeg"),
                  // CachedNetworkImage(imageUrl: "http://b1-q.mafengwo.net/s9/M00/A6/9B/wKgBs1d2CP-AA0h4AAFcgA8zsz885.jpeg"),
                  // CachedNetworkImage(imageUrl: "http://p1-q.mafengwo.net/s9/M00/A6/A4/wKgBs1d2CRCAUNqoAACbBSzN6oA11.jpeg"),
                ],
              ))),
          Row(
            children: [
              GestureDetector(
                child: Container(
                  child:
                  Column(children: [Icon(CupertinoIcons.cube), Text("店铺")]),
                  width: ScreenUtil().setWidth(58),
                  decoration: BoxDecoration(),
                ),
                onTap: (){
                  MyRoute.pop();
                },
              ),
            GestureDetector(
              child:   Container(
                  width: ScreenUtil().setWidth(58),
                  child: Column(children: [
                    Icon(CupertinoIcons.headphones),
                    Text("客服")
                  ])),
              onTap: (){
                print("找客服");
              },
            ),
              GestureDetector(
                child: Container(
                  width: ScreenUtil().setWidth(58),
                  child: Column(
                    // children: [Icon(CupertinoIcons.star), Text("收藏")])),
                  children: [
                    guanzhu ? Icon(Icons.star,color: Colors.orange,) : Icon(Icons.star_border),
                    Text("收藏")
                  ],)),
                onTap: () async {
                  print("收藏服务");
                  var map = new HashMap<String,dynamic>();
                  map['gid']=gid;map['type']=1;map['userId']=userId;
                  Response response = await HttpUtil().post("waimai/mCollect/collect",map);
                  var x = json.decode(response.toString());
                  if(x['code']==200){
                    if(guanzhu){
                      guanzhu = false;
                    }else{
                      guanzhu = true;
                    }
                  }
                  Fluttertoast.showToast(msg: x['msg']);
                  setState(() {

                  });
                },
              ),
              GestureDetector(
                child: Container(
                  width: ScreenUtil().setWidth(290),
                  height: ScreenUtil().setHeight(50),
                  child: Center(
                      child: Text(
                        "立即预约",
                        style: TextStyle(color: Colors.white),
                      )),
                  decoration: BoxDecoration(color: Colors.red),
                ),
                onTap: () async {
                  SharedPreferences prefs =
                  await SharedPreferences.getInstance();
                  // String userId = prefs.getString("userId");//用户ID
                  bool isLogin = prefs.getBool("isLogin");
                  if (!isLogin) {
                    Fluttertoast.showToast(msg: "请先登录");
                    Future.delayed(Duration(seconds: 2), () {
                      MyRoute.replace(Login());
                    });
                  } else {
                    MyRoute.push(YuYueService(gid: obj['id'],gName: obj['gname'],merchantId: obj['mid'],));
                  }
                },
              )
            ],
          )
        ],
      ));
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (CachedNetworkImage(
      imageUrl: _imageUrls[index],
      fit: BoxFit.fill,
    ));
  }

  // Set selectGuige=new Set(); // 选择的规格
  // var map = new Map();//选择的规格
  //显示规格
  Widget _showGuige(aaa) {
    return StatefulBuilder(builder: (context1, setBottomSheetState) {
      funCb = setBottomSheetState;
      return Container(
        height: 350.0,
        child: Column(
          children: [
            Text("请选择规格"),
            Divider(),
            Container(
              child: Row(
                children: [
                  CachedNetworkImage(
                    imageUrl: Config.getInstance().getHost() + obj['gimages'],
                    width: 60,
                    height: 60,
                  ),
                  Column(
                    children: [
                      // Text("￥${obj['gprice']}"),
                      Text("￥${money}"),
                    ],
                  ),
                ],
              ),
            ),
            _showGuigeDetail(),
            Expanded(
                child: Stack(
                  children: [
                    Positioned(
                      bottom: 0,
                      left: ScreenUtil().setWidth(180),
                      child: GestureDetector(
                        child: Center(
                          child: Container(
                            child: Text("确定"),
                            padding: EdgeInsets.symmetric(vertical: 10,horizontal: 30),
                            decoration: BoxDecoration(color: Colors.orangeAccent),
                          ),
                        ),
                        onTap: () async {
                          // setBottomSheetState(() {
                          //   // 此句代码可用更新选择的规格价格
                          // });
                          // print("点击了确定");
                          int n = guige['select_guiges'].length;
                          int m = names.length;
                          if (m < n) {
                            Fluttertoast.showToast(msg: "请选择完整规格");
                            return;
                          }
                          params = params.sublist(params.length - n);
                          names = names.sublist(names.length - n);
                          if (m > 1) {
                            //排序
                            for (int i = 0;
                            i < guige['select_guiges'].length;
                            i++) {
                              if (guige['select_guiges'][i]['name'] != panduan[i]) {
                                for (int e = 0; e < panduan.length; e++) {
                                  if (guige['select_guiges'][i]['name'] ==
                                      panduan[e]) {
                                    var z = panduan[i];
                                    panduan[i] = panduan[e];
                                    panduan[e] = z;
                                    var y = names[i];
                                    names[i] = names[e];
                                    names[e] = y;
                                    var o = params[i];
                                    params[i] = params[e];
                                    params[e] = o;
                                  }
                                }
                              }
                            }
                          }
                          if (params.length == 1) {
                            money =
                                double.parse(guige['values'][params[0]]['jiage']);
                          } else if (params.length == 2) {
                            money = double.parse(guige['values'][params[0]]
                            ['children'][params[1]]['jiage']);
                          } else {
                            money = double.parse(guige['values'][params[0]]
                            ['children'][params[1]]['children'][params[2]]
                            ['jiage']);
                          }
                          // guiges = names.toString();//规格
                          // guigexiabiao = params.toString();//规格下标
                          // print("规格："+guiges);
                          // print("规格下标："+guigexiabiao);
                          // guiges = guiges.substring(1,guiges.length-1);
                          // guigexiabiao = guigexiabiao.substring(1,guigexiabiao.length-1);
                          guiges = json.encode(names);
                          guigexiabiao = json.encode(params);
                          // print("规格："+guiges);
                          // print("规格下标："+guigexiabiao);
                          if (aaa == 1) {
                            // print("规格价格："+money.toString());
                            var x = await HttpUtil().get(
                                "/app/shopCat/addGoodscat?gid=" +
                                    "${obj['gid']}" +
                                    "&userId=" +
                                    userId +
                                    "&catnum=1" +
                                    "&names=" +
                                    guiges +
                                    "&params=" +
                                    guigexiabiao +
                                    "&money=" +
                                    money.toString());
                            if (x['code'] == 200) {
                              Fluttertoast.showToast(msg: "加入购物车成功");
                            } else {
                              Fluttertoast.showToast(msg: x['msg']);
                            }
                            // print(params);
                            // print(names);
                            // print(panduan);
                            // var x = selectGuige.toSet();
                            // print(x);
                            Navigator.pop(context); // 隐藏底部规格选择
                            names = [];
                            params = [];
                            panduan = [];
                          } else {
                            String gid = obj['gid'];
                            MyRoute.push(LjgmOrder(
                                gid: gid,
                                names: guiges,
                                params: guigexiabiao,
                                money: money));
                          }
                        },
                      ),
                    )
                  ],
                ))
          ],
        ),
      );
    });
  }

  // 循环显示规格界面中的参数
  Widget _showGuigeDetail() {
    // names = [];
    // params = [];
    // panduan = [];
    List<Widget> col = [];
    // print(guige);
    // print(guige['select_guiges']);
    for (var i = 0; i < guige['select_guiges'].length; i++) {
      // print(guige['select_guiges'][i]['values']);
      List<String> x = [];
      for (var j = 0; j < guige['select_guiges'][i]['values'].length; j++) {
        x.add(guige['select_guiges'][i]['values'][j]['value'].toString());
      }
      col.add(Align(
        child: Text(guige['select_guiges'][i]['name']),
        alignment: Alignment.topLeft,
      )); // 规格名称
      col.add(GroupButton(
          isRadio: true,
          spacing: 10,
          onSelected: (index, isSelected) {
            int n = -1;
            if (panduan.contains(guige['select_guiges'][i]['name'])) {
              for (var x = 0; x < names.length; x++) {
                var ttt = names[x][guige['select_guiges'][i]['name']];
                if (ttt != null && ttt != "") {
                  n = x;
                  break;
                }
              }
            }
            int xiabiao = int.parse('$index');
            if (n == -1) {
              // true
              panduan.add(guige['select_guiges'][i]['name']);
              params.add(xiabiao);
              names.add({
                guige['select_guiges'][i]['name']: guige['select_guiges'][i]
                ['values'][xiabiao]['value']
              });
            } else {
              params[n] = xiabiao;
              names[n][guige['select_guiges'][i]['name']] =
              guige['select_guiges'][i]['values'][xiabiao]['value'];
            }
            if (params.length == guige['select_guiges'].length) {
              if (params.length == 1) {
                money = double.parse(guige['values'][params[0]]['jiage']);
              } else if (params.length == 2) {
                money = double.parse(
                    guige['values'][params[0]]['children'][params[1]]['jiage']);
              } else {
                money = double.parse(guige['values'][params[0]]['children']
                [params[1]]['children'][params[2]]['jiage']);
              }
              print("规格金额：" + money.toString());
            }
            // 此处更新显示的规格价格
            funCb(() {});
          },
          buttons: x));
    }
    return Container(
      child: Column(children: col),
    );
  }
}
